package com.xiaobai.netease_news.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Set;
import java.util.zip.GZIPInputStream;

/**
 * Created by Android Studio
 * Project: NeteaseNews
 * Author: Jack
 * Email: jackfangqi1314@gmail.com/jackfangqi@163.com
 * Date: 2015/6/3
 */
public class CommonHttpUtil {
    public static final int TIME_OUT = 5000;

    private CommonHttpUtil() {
    }

    public static byte[] doGet(String url) {
        return doGet(url, null);
    }

    /**
     * ????GET?????????????????????????????????????????????????????????????????????????????
     *
     * @param url
     * @param headers
     * @return
     */
    public static byte[] doGet(String url, HashMap<String, String> headers) {
        byte[] data = null;

        if (url != null) {
            try {
                URL u = new URL(url);
                HttpURLConnection connection = (HttpURLConnection) u.openConnection();
                // 1????????????????????GET
                connection.setRequestMethod("GET");
                // 2???????????????????????????????close??????????????????????????Socket????
                // keep-alive?????????????????????????????????????Socket
                // ????????????????????
                connection.setRequestProperty("Connection", "keep-alive");
                // 3?????????????????ser-Agent????????????????????????????????????????????
                connection.setRequestProperty("User-Agent", "CommonHttpUtil/1.0 [Android]");

                // TODO ??????HTTP????????????
                if (headers != null) {
                    Set<String> keySet = headers.keySet();
                    for (String key : keySet) {
                        String value = headers.get(key);
                        connection.setRequestProperty(key, value);
                    }
                }

                // TODO ??????????
                // ??????????????????????????????????????????????????
                connection.setConnectTimeout(TIME_OUT);
                // ????????????????????????????????
                connection.setInstanceFollowRedirects(true);
                // ??????????????????????????????????????????????????????????????????????????????????????????????????
                connection.setReadTimeout(TIME_OUT);
                // ??????????????
                connection.connect();
                // ????????????????????????????????????
                int responseCode = connection.getResponseCode();
                if (responseCode == 200) {
                    InputStream inputStream = connection.getInputStream();
                    // ????????????????????????????????????????
                    String contentEncoding = connection.getContentEncoding();
                    // ?????ontentEncoding?????????????????????
                    if (contentEncoding != null) {
                        if (contentEncoding.equals("gzip")) {
                            // ???? Content-Encoding:gzip
                            inputStream = new GZIPInputStream(inputStream);
                        } else {
                            // TODO ????????zip????????
                        }
                    }
                    // TODO ??????????????
                    data = StreamUtil.readStream(inputStream);
                    inputStream.close();
                } else {

                }

                // ????????????????
                connection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return data;
    }

    /**
     * POST???????????key=value&key=value????????????????
     *
     * @param url
     * @param params
     * @param headers
     * @return
     */
    public static byte[] doPost(String url, HashMap<String, String> params, HashMap<String, String> headers) {
        byte[] data = null;

        if (url != null) {
            try {
                URL u = new URL(url);
                HttpURLConnection connection = (HttpURLConnection) u.openConnection();

                // 1????????????
                connection.setRequestMethod("POST");
                // 2???Connection???User-Agent??????????
                connection.setRequestProperty("Connection", "keep-alive");
                connection.setRequestProperty("User-Agent", "CommonHttpUtil/1.0 [Android]");
                // 3???Http??????
                // TODO ?????????POST????????????????????????ontent-Type????????????????????????????????????????????????????
                // ???????????????Key=value????????????????????????????????????
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                // ??????????????????????????????????????????????????
                connection.setConnectTimeout(TIME_OUT);
                // ????????????????????????????????
                connection.setInstanceFollowRedirects(true);
                // ??????????????????????????????????????????????????????????????????????????????????????????????????
                connection.setReadTimeout(TIME_OUT);

                if (headers != null) {
                    Set<String> keySet = headers.keySet();
                    for (String key : keySet) {
                        String value = headers.get(key);
                        connection.setRequestProperty(key, value);
                    }
                }

                // POST????????????????????????????????????
                connection.setDoInput(true);
                if (params != null) {
                    if (!params.isEmpty()) {
                        // ??????????????????????
                        connection.setDoOutput(true);
                    }
                }

                // ??????
                connection.connect();

                // ??????????
                if (params != null && !params.isEmpty()) {
                    // user=admin&pass=123
                    StringBuilder stringBuilder = new StringBuilder();
                    Set<String> keySet = params.keySet();
                    // ??????????????????
                    for (String key : keySet) {
                        String value = params.get(key);
                        stringBuilder.append(URLEncoder.encode(key, "utf-8")).append("=")
                                .append(URLEncoder.encode(value, "utf-8")).append("&");
                    }
                    stringBuilder.deleteCharAt(stringBuilder.length() - 1); // ??????????????&
                    String requestStr = stringBuilder.toString();

                    byte[] d = requestStr.getBytes();

                    // ???????????????????????????Content-Length??????????????????????????
                    connection.setRequestProperty("Content-Length", String.valueOf(d.length));

                    // ????????????
                    OutputStream outputStream = connection.getOutputStream();   // ????????????
                    outputStream.write(d);
                    outputStream.flush();
                    outputStream.close();
                }

                // ??????????????????????
                int responseCode = connection.getResponseCode();
                // ??????????????responseCode??????????????????????????????????
                InputStream inputStream = connection.getInputStream();
                if (inputStream != null) {
                    // TODO ??????????????????
                    String contentEncoding = connection.getContentEncoding();
                    if ("gzip".equals(contentEncoding)) {
                        inputStream = new GZIPInputStream(inputStream);
                    }

                    data = StreamUtil.readStream(inputStream);
                    inputStream.close();
                }

                connection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return data;
    }
}
